package com.example.yt_app.Urils;

/**
 * Created by dell on 2021/7/12.
 */
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author dell
 */
@SuppressWarnings("ALL")
public class AESUtils3 {
    /**   算法/模式/填充 */
    @SuppressWarnings("AlibabaConstantFieldShouldBeUpperCase")
    private static final String CipherMode = "AES/ECB/PKCS5Padding";

    /**  创建密钥  */
    @SuppressWarnings("AlibabaUndefineMagicConstant")
    private static SecretKeySpec createKey(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
        StringBuffer sb = new StringBuffer(32);
        sb.append(password);
        //noinspection AlibabaUndefineMagicConstant
        while (sb.length() < 32) {
            sb.append("0");
        }
        //noinspection AlibabaUndefineMagicConstant
        if (sb.length() > 32) {
            sb.setLength(32);
        }

        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }

    /** 加密字节数据  */
    public static byte[] encrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            System.out.println(key);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**加密(结果为16进制字符串)  */
    public static String encrypt(String content, String password) {
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password);
        String result = byte2hex(data);
        return result;
    }

    /**解密字节数组*/
    public static byte[] decrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**解密16进制的字符串为字符串  */
    public static String decrypt(String content, String password) {
        byte[] data = null;
        try {
            data = hex2byte(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password);
        if (data == null) {
            return null;
        }
        String result = null;
        try {
            result = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
    *字节数组转成16进制字符串  */
    public static String byte2hex(byte[] b) { // 一个字节的数，
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            // 整数转成十六进制表示
            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }

    /*将hex字符串转换成字节数组 */
    @SuppressWarnings({"AlibabaUndefineMagicConstant", "AlibabaCommentsMustBeJavadocFormat"})
    private static byte[] hex2byte(String inputString) {
        //noinspection AlibabaUndefineMagicConstant
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
    /**
    * 雅图教育密码验证方法
    * */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public static String encrypt(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(str.getBytes("utf-8"));

            final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
            StringBuilder ret = new StringBuilder(bytes.length * 2);
            for (int i = 0; i < bytes.length; i++) {
                ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
                ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
            }
            return ret.toString().toLowerCase();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 登录验证，密码加密
     * */
    @SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaUndefineMagicConstant"})
    public static String encryptSalt(String str) {
        // 生成一个16位的随机数
        Random random = new Random();
        StringBuilder sBuilder = new StringBuilder(16);
        sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
        int len = sBuilder.length();
        //noinspection AlibabaUndefineMagicConstant
        if (len < 16) {
            //noinspection AlibabaUndefineMagicConstant
            for (int i = 0; i < 16 - len; i++) {
                sBuilder.append("0");
            }
        }
        String Salt = sBuilder.toString();
        str = encrypt(encrypt(str) + Salt);
        char[] cs = new char[48];
        //noinspection AlibabaUndefineMagicConstant
        for (int i = 0; i < 48; //noinspection AlibabaUndefineMagicConstant
             i += 3) {
            cs[i] = str.charAt(i / 3 * 2);
            char c = Salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = str.charAt(i / 3 * 2 + 1);
        }
        return String.valueOf(cs);
    }
}
